package com.android.hdhe.uhf.main;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.android.hdhe.uhf.reader.CaseString;
import com.android.hdhe.uhf.reader.Tools;
import com.android.hdhe.uhf.reader.UhfReader;

import java.util.ArrayList;
import java.util.List;
/**
* @Package com.android.hdhe.uhf.main 
* @Description: TODO(扫描工具类) 
* @author 郑鸿博   
* @date 2015-12-4 下午1:58:29 
* @version V1.0
 */
public class SaomiaoUtil{

	private static final String TAG = "SaomiaoUtil";

	public SaomiaoUtil(UhfReader reader) {
		super();
		this.reader = reader;
	}
	InventoryThread thread;
	private UhfReader reader ; //超高频读写器 
	private boolean runFlag = true;
	private boolean startFlag = true;
	private List<String> list = new ArrayList<String>();
	private Handler handler;
	
	
	public void setHandler(Handler handler) {
		this.handler = handler;
	}
	/**
	 * 清空
	 */
	public void clear(){
		list.clear();
	}
	/**
	 * 暂时关闭扫描功能
	 */
	public void close(){
		//runFlag = false ;
		startFlag = false ;
	}
	/**
	 * 暂时开启扫描功能
	 */
	public void open(){
		//runFlag = true ;
		startFlag = true ;
	}
	
	public void waiting(){
		try {
			
			thread.wait();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void notifys(){
		try {
			thread.notify();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 过滤器
	 * @param str
	 * @return
	 */
	public String Guolv(String str){
		String box = CaseString.getBoxNum(str);//这个方法以后自己去修改
		if(box.length()<2){
			return "";
		}
		String stx = box.substring(box.length()-2, box.length());
		if("ZZ".equals(stx)){
			return box;
		}else{
			return "箱子规格不正确";
		}
	//	return box;
	}
	
	public void start(){
		if(thread==null){
			thread = new InventoryThread();
			thread.start();
		}else{
			thread.start();
		}
	}
	
	/**
	 * 盘存线程
	 * @author Administrator
	 */
	class InventoryThread extends Thread{
		private List<byte[]> epcList;
		@Override
		public void run() {
			super.run();
			while(runFlag){
				String strBox = null;
			
				if(startFlag){
//					
					;
					Log.e(TAG,"扫描");
					epcList = reader.inventoryRealTime(); //实时盘存
					if(epcList != null && !epcList.isEmpty()){
						//播放提示音
					//	Util.play(1, 0);
						for(byte[] epc:epcList){
							String epcStr = Tools.Bytes2HexString(epc, epc.length);
//							strBox = Guolv(epcStr);

							strBox=epcStr;
							Message msg = new Message();
							msg.obj = strBox ;
							msg.what =0;
							if(null != strBox && !"".equals(strBox)){
						//		Util.play(1, 0);
								handler.sendMessage(msg);
							}
						}
					}		
					epcList = null ;
					try {
						Thread.sleep(20);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
}
